const express = require('express');
const router = express.Router();
const prisma = require('../utils/prisma.js');
const resultResponse = require('../utils/response.js');

router.get('/test', async (req, res) => {
  const user = await prisma.users.findMany();
  return res.send(user);
});

/** 登录 */
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const count = await prisma.users.count({
      where: {
        username,
      },
    });
    if (count === 0) return res.send(resultResponse('false', '用户不存在'));
    const user = await prisma.users.findFirst({
      select: {
        id: true,
        email: true,
        user_roles: {
          select: {
            role_id: true,
            roles: {
              select: {
                name: true,
                role_permissions: {
                  select: {
                    permissions: {
                      select: {
                        name: true,
                        type: true,
                      },
                    },
                  },
                },
              },
            },
          },
        },
      },
      where: {
        username,
        password,
      },
    });
    console.log(user);
    const userInfo = {
      user_id: user.id,
      email: user.email,
      role: {
        name: user.user_roles[0].roles.name,
        menus: user.user_roles[0].roles.role_permissions
          .filter(i => {
            if (i.permissions.name && i.permissions.type === 'route') {
              return i.permissions.name;
            }
          })
          .map(m => m.permissions.name),
        points: user.user_roles[0].roles.role_permissions
          .filter(i => {
            if (i.permissions.name && i.permissions.type === 'button') {
              return i.permissions.name;
            }
          })
          .map(p => p.permissions.name),
      },
    };
    return res.send(resultResponse('true', userInfo));
  } catch (error) {
    return res.send(resultResponse('false', error.message));
  }
});
/** 注册/添加用户 */
router.post('/register', async (req, res) => {
  try {
    const { username, password, email } = req.body;
    const count = await prisma.users.count({
      where: {
        username,
      },
    });
    if (count > 0) return res.send(resultResponse('false', '用户已存在'));
    const user = await prisma.users.create({
      data: {
        username,
        password,
        email,
        user_roles: {
          create: {
            role_id: 2, // 新用户 -> 给角色 -> 普通用户
          },
        },
      },
    });
    return res.send(resultResponse('true', { ...user, password: undefined }));
  } catch (error) {
    return res.send(resultResponse('false', error.message));
  }
});

/** 编辑用户角色 */
router.put('/update/role', async (req, res) => {
  try {
    // 该步骤先要校验身份是否为超级管理，为管理员才能进行操作，此处为了演示先省略
    const { user_id, role_id } = req.body;
    const old_role_id = await prisma.user_roles
      .findFirst({
        where: {
          user_id,
        },
        select: {
          role_id: true,
        },
      })
      .then(res => res.role_id);
    if (!old_role_id) return res.send(resultResponse('false', 'user_id有误'));
    const user = await prisma.user_roles.upsert({
      where: {
        user_id_role_id: {
          user_id,
          role_id: old_role_id,
        },
      },
      update: {
        role_id,
      },
      create: {
        role_id,
        user_id,
      },
    });
    return res.send(resultResponse('true', user));
  } catch (error) {
    console.log(error.message);
    return res.send(resultResponse('false', error.message));
  }
});

/** 添加权限 */
router.post('/add/permission', async (req, res) => {
  try {
    const { name, type } = req.body;
    // 添加前检验当前角色是否为管理员，否则不给操作 此处演示省略此步骤
    const user = await prisma.permissions.create({
      data: {
        name,
        type,
      },
    });
    if (!user.id) return res.send(resultResponse('false', '添加失败'));
    return res.send(resultResponse('true', '添加成功'));
  } catch (error) {
    console.log(error.message);
    return res.send(resultResponse('false', error.message));
  }
});

router.post('/add/role/permission', async (req, res) => {
  try {
    const { role_id, permission_id } = req.body;
    const addRolePermission = await prisma.role_permissions.create({
      data: {
        role_id,
        permission_id,
      },
    });
    if (!addRolePermission) return res.send(resultResponse('false', '添加失败'));
    return res.send(resultResponse('true', '添加成功'));
  } catch (error) {
    console.log(error.message);
    return res.send(resultResponse('false', error.message));
  }
});

module.exports = router;
